<?php

if (!defined('IN_XLP')) {
    exit('Access Denied!');
}
/*
 * 微信登录API
 */

class loginApi {

    const API_URL_PREFIX = 'https://api.weixin.qq.com/cgi-bin';
    const OAUTH_PREFIX = 'https://open.weixin.qq.com/connect/oauth2';
    const OAUTH_AUTHORIZE_URL = '/authorize?';
    const OAUTH_TOKEN_PREFIX = 'https://api.weixin.qq.com/sns/oauth2';
    const OAUTH_TOKEN_URL = '/access_token?';
    const OAUTH_REFRESH_URL = '/refresh_token?';
    const OAUTH_USERINFO_URL = 'https://api.weixin.qq.com/sns/userinfo?';

    private $appid;
    private $appsecret;
    private $userToken;
    public $scope = 'snsapi_userinfo';
    public $errCode = 0;
    public $errMsg = 'no access';

    public function __construct($options = array()) {
        $this->appid = isset($options['appid']) ? $options['appid'] : '';
        $this->appsecret = isset($options['appsecret']) ? $options['appsecret'] : '';
        if (!$this->appid || !$this->appsecret) {
            $setting = F('weixin/setting');
            if (isHave($setting['user_info']['wx_AppId']) && isHave($setting['user_info']['wx_AppSecret'])) {
                $this->appid = $setting['user_info']['wx_AppId'];
                $this->appsecret = $setting['user_info']['wx_AppSecret'];
            } else {
                showError('api Error:请设置appid和appsecret');
            }
        }
    }

    /**
     * oauth 授权跳转接口
     * @param string $callback 回调URI
     * @return string
     */
    public function getOauthRedirect($callback, $scope = 'base') {
        if ($scope == 'base') {
            $this->scope = 'snsapi_login';
            $state = 1;
        } else {
            $this->scope = 'snsapi_userinfo';
            $state = 2;
        }
        return self::OAUTH_PREFIX . self::OAUTH_AUTHORIZE_URL . 'appid=' . $this->appid . '&redirect_uri=' . urlencode($callback) . '&response_type=code&scope=' . $this->scope . '&state=' . $state . '#wechat_redirect';
    }

    /*
     * 通过code获取Access Token
     * @return array {accessToken,expires_in,refresh_token,openid,scope}
     */

    public function getOauthAccessToken($code = '', $state = 1) {
        $state = ($state == 2) ? 2 : 1;
        if (!$code || $code == 'authdeny') {//禁止授权
            $this->errCode = -1;
            $this->errMsg = '用户未授权';
            return false;
        }
        $result = getHttp(self::OAUTH_TOKEN_PREFIX . self::OAUTH_TOKEN_URL . 'appid=' . $this->appid . '&secret=' . $this->appsecret . '&code=' . $code . '&grant_type=authorization_code');
        if ($result) {
            $json = json_decode($result, true);
            if (!$json || !empty($json['errcode'])) {
                $this->errCode = $json['errcode'];
                $this->errMsg = '未授权-' . $json['errmsg'];
                return false;
            }
            $this->userToken = $json['access_token'];
            $this->openId = $json['openid'];
            if ($state == 2) {
                $json = $this->getOauthUserinfo();
            }
            $json['state'] = $state;
            return $json;
        }
        return false;
    }

    /**
     * 刷新access token并续期
     * @param string $refresh_token
     * @return boolean|mixed
     */
    public function getOauthRefreshToken($refresh_token) {
        $result = getHttp(self::OAUTH_TOKEN_PREFIX . self::OAUTH_REFRESH_URL . 'appid=' . $this->appid . '&grant_type=refresh_token&refresh_token=' . $refresh_token);
        if ($result) {
            $json = json_decode($result, true);
            if (!$json || !empty($json['errcode'])) {
                $this->errCode = $json['errcode'];
                $this->errMsg = $json['errmsg'];
                return false;
            }
            $this->userToken = $json['access_token'];
            return $json;
        }
        return false;
    }

    /**
     * 获取授权后的用户资料
     * @param string $accessToken
     * @param string $openid
     * @return array {openid,nickname,sex,province,city,country,headimgurl,privilege}
     */
    private function getOauthUserinfo() {
        if (!$this->userToken || !$this->openId) {
            $this->errCode = -2;
            $this->errMsg = '未授权或者openid丢失';
            return false;
        }
        $result = getHttp(self::OAUTH_USERINFO_URL . 'access_token=' . $this->userToken . '&openid=' . $this->openId);
        if ($result) {
            $json = json_decode($result, true);
            if (!$json || !empty($json['errcode'])) {
                $this->errCode = $json['errcode'];
                $this->errMsg = $json['errmsg'];
                return false;
            }
            return $json;
        }
        return false;
    }

}
